/*UserToPerson control class*/
$N.ctrl.UserToPersonCtrl = (function () {
	var notify;

	function getUserToPersonData() {
		var userName = $N.util.getUserName();
		$N.databaseSet.UserToPersonTable.getUserToPersonData(userName, _sqlResponseCb);
	}
	function _downloadUserToPersonData() {
		var postURL = "http://localhost/cakephp/mobileUsersAdapter/mobileusertopersonsdown";
		var para = {
			jsonstring : JSON.stringify({
				username : "hello"
			})
		};
		$N.util.ajaxPost(postURL, para, _ajaxResponseCb);
	}

	function _sqlResponseCb(tx, result) {
		if (result.rows.length != 0) {
			for (var i = 0; i < result.rows.length; i++) {
				notify(result.rows.item(i));
			}
		} else {
			_downloadUserToPersonData();
		}
	}

	function _ajaxResponseCb(jsonResponse) {
		if (jsonResponse.length == 0) {
			//put a placeholder
			console.log("json_response string is empty.");
		} else {
			if (jsonResponse.search("NO MORE") != -1) {
				return;
			}
			jsonObject = JSON.parse(jsonResponse);
			//save data into the database
			for (var i = 0; i < jsonObject.length; i++) {
				var data = jsonObject[i].UserToPerson;
				$N.databaseSet.UserToPersonTable.addUserToPersonData(data);
				/*get personProfile data*/
				notify(data);
			}
		}
	}

	function registerClientNotify(notifyCb) {
		notify = notifyCb;
	}

	function _detachPersonsCallback(jsonResponse) {
		if (response.indexof('OK') !== -1) {
			$N.util.showDialog('解除用户', '成功', null, null);
			return;
		}

	}
	function detachManagedPersons(detachedManagedPersonsArray, notifyCb) {
		var postURL = $N.util.getDetachManagedPersonsURL();

		if (typeof detachedManagedPersonsArray !== 'Array') {
			var para = {
				jsonstring : JSON.stringify({username : 'hello',
											 personIDs: detachedManagedPersonsArray
											 })
			};	
				
			$N.util.ajaxPost(postURL, para, function (jsonResponse) {
				if (jsonResponse.indexOf('OK') !== -1 || jsonResponse.indexOf('NO MORE') !== -1) {
					if (notifyCb != null) {
						notifyCb(true);
					}
				} else {
					if (notifyCb != null) {
						notifyCb(false);
					}
				}
				return;
			});
			return;
		}
	}
	return {
		getUserToPersonData : getUserToPersonData,
		registerClientNotify : registerClientNotify,
		downloadUserToPersonData : _downloadUserToPersonData,
		detachManagedPersons : detachManagedPersons
	};
}
	());
